﻿using System;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using System.Text;
using Texfina.Core.Common;
using Texfina.Common.Mg;
using Texfina.Core.Web;
using Texfina.Core.Data;
using Texfina.Entity.Rh;
using Texfina.Entity.Mg;
using Texfina.Entity.Sy;
using RHBOQry = Texfina.BOQry.Rh;
using MGBOQry = Texfina.BOQry.Mg;
using RHBOMnt = Texfina.BOMnt.Rh;
using SYBOQry = Texfina.BOQry.Sy;
using System.IO;

namespace RH
{
   public partial class wfImportDataMnt : EditPage
   {
      /// <summary>
      /// Guarda el estado de un DataTable, usado para llenar los dropdownlist del grdList.
      /// </summary>
      /// <value></value>
      /// <returns></returns>
      public DataTable DataSourceDrop
      {
         get { return (DataTable)this.ViewState["_dsDrop"]; }
         set { this.ViewState["_dsDrop"] = value; }
      }

      /// <summary>
      /// Guarda el estado de un DataTable, usado para Guardar temporalmente data de un archivo Excel.
      /// </summary>
      /// <value></value>
      /// <returns></returns>
      public DataTable DataSourceExcel
      {
         get { return (DataTable)this.ViewState["_dsXls"]; }
         set { this.ViewState["_dsXls"] = value; }
      }

      /// <summary>
      /// Guarda el estado de un DataTable, usado para Guardar Datos finales para ser guardados.
      /// </summary>
      /// <value></value>
      /// <returns></returns>
      public DataTable DataSourceData
      {
         get { return (DataTable)this.ViewState["_dsData"]; }
         set { this.ViewState["_dsData"] = value; }
      }

      /// <summary>
      /// Guarda el estado de un string[], usado para guardar la Cadena de Conexion excel ah subir.
      /// </summary>
      /// <value></value>
      /// <returns></returns>
      public string[] GetConnection
      {
         get { return (string[])this.ViewState["_dsFUpload"]; }
         set { this.ViewState["_dsFUpload"] = value; }
      }

      /// <summary>
      /// Guarda el estado de un string, usado para controlar el registro o modificacion de datos.
      /// </summary>
      /// <value></value>
      /// <returns></returns>
      public string StDatosGenerados
      {
         get { return (string)this.ViewState["_dsDaGen"]; }
         set { this.ViewState["_dsDaGen"] = value; }
      }

      public const int _GRDLIST_IDHORA = 2;
      public const int _GRDLIST_STIDPERSONAL = 5;
      public const int _GRDLIST_STANULADO = 8;

      public const string _BUTTON_IMPORTFIELD = "_BTTIMPFIELD";
      public const string _BUTTON_IMPORTDATA = "_BTTIMPDATA";
      public const string _BUTTON_GENERATEDOC = "_BTTGENEDOC";
      public const string _BUTTON_IMPVACA = "_BTTIMPVACA";
      protected void Page_Load(object sender, EventArgs e)
      {
         if (this.IsPostBack)
         {
            this.LoadInPostBack();
            return;
         }
         this.LoadData();
      }

      public override void LoadInPostBack()
      {
         foreach (GridViewRow gvr in this.grdListData.Rows)
         {
            if (gvr.RowType == DataControlRowType.DataRow)
            {

               int intIdx = 0;

               if (this.StDatosGenerados == ConstFlagEstado.ACTIVADO)
               {
                  foreach (DataRow dr in this.DataSource.Rows)
                  {
                     if ("" != dr["idHora"].ToString())
                     {
                        gvr.Cells[intIdx].Text = Request.Form[gvr.UniqueID + "$colum_" + gvr.RowIndex + "_" + intIdx.ToString()];
                     }
                     intIdx++;
                  }
               }
               else
               {
                  foreach (DataControlFieldCell dc in gvr.Cells)
                  {
                     if (((System.Web.UI.WebControls.BoundField)(dc.ContainingField)).DataField != "idPersonal" && ((System.Web.UI.WebControls.BoundField)(dc.ContainingField)).DataField != "dsApeNombres")
                     {
                        dc.Text = Request.Form[gvr.UniqueID + "$colum_" + gvr.RowIndex + "_" + intIdx.ToString()];
                     }
                     intIdx++;
                  }

               }
            }
         }


         this.RegisterGeneralScripts();
      }

      public override void LoadInitialSettings()
      {
         this.FormEditAction = (FormEditAction)Enum.Parse(typeof(FormEditAction), Request.QueryString["formEA"]);
         this.SetInitialTitle("Importar Datos");
         this.mnuGrid.Items[2].ImageUrl = "../Images/Icons/Disabled/ImportTable.png";

         //switch (Request.QueryString["IdPlanilla"].ToString())
         // {
         //     case "005" :
         //     case "006" :
         //     case "007" :
                    
         //         break;
          
         // }
      }

      public override void LoadListControls()
      {
         EHora objE = new EHora();
         IBOQuery objBO = (IBOQuery)WCFHelper.GetObject<IBOQuery>(typeof(RHBOQry.Hora));
         objE.IdEmpresa = Session[ConstSessionVar.EMPRESA].ToString();
         this.DataSourceDrop = objBO.GetList(objE);

         this.ddlidTipoMigra.Items.Add(new ListItem("Horas", ConstTipoMigracion.HORAS));
         this.ddlidTipoMigra.Items.Add(new ListItem("Regularizacion", ConstTipoMigracion.REGULARIZACION));
         this.ddlidTipoMigra.Items.Add(new ListItem("Bonificacion", ConstTipoMigracion.BONIFICACION));

         //ctl.Items.Add(new ListItem("", ""));
      }

      public override void DataToControls()
      {
         EProcPlani objE = new EProcPlani();
         IBOQuery objBO = (IBOQuery)WCFHelper.GetObject<IBOQuery>(typeof(RHBOQry.ProcPlani));
         objE.IdPeriodo = Session[ConstSessionVar.PERIODO].ToString();
         objE.IdEmpresa = Session[ConstSessionVar.EMPRESA].ToString();
         objE.IdMes = Request.QueryString["IdMes"];
         objE.IdForPago = Request.QueryString["idForPago"];
         objE.IdPlanilla = Request.QueryString["IdPlanilla"];

         if (Request.QueryString["NuProcAnual"] != null)

            objE.NuProcAnual = Convert.ToInt16(Request.QueryString["NuProcAnual"]);

         this.txtNroProcAnual.Text = Request.QueryString["NuProcAnual"];
         objE = (EProcPlani)objBO.GetByKey(objE);


         if (objE != null)
         {
            WebHelper.EntityToControl(objE, "IdPlanilla", txtidPlanilla);

            EPlanilla objEPla = new EPlanilla();
            IBOQuery objBOPla = (IBOQuery)WCFHelper.GetObject<IBOQuery>(typeof(RHBOQry.Planilla));
            objEPla.IdEmpresa = Session[ConstSessionVar.EMPRESA].ToString();
            objEPla.IdPlanilla = Request.QueryString["IdPlanilla"];
            objEPla = (EPlanilla)objBOPla.GetByKey(objEPla);
            if (objEPla != null)
               WebHelper.EntityToControl(objEPla, "DsPlanilla", txtdsPlanilla);

         }

         MGBOQry.ITablaGen objBOI = (MGBOQry.ITablaGen)WCFHelper.GetObject<MGBOQry.ITablaGen>(typeof(MGBOQry.TablaGen));
         ETablaGenDet objEDet = new ETablaGenDet();
         objEDet.IdTabla = ConstMultitabla.FORMA_PAGO;
         objEDet.IdCodigo = Request.QueryString["idForPago"];
         objEDet = (ETablaGenDet)objBOI.GetDetailByKey(objEDet);

         if (objEDet != null)
            WebHelper.EntityToControl(objEDet, "DsDescrip", txtdsFormaPago);

         EConfigHora objECH = new EConfigHora();
         IBOQuery objBOCH = (IBOQuery)WCFHelper.GetObject<IBOQuery>(typeof(SYBOQry.ConfigHora));
         objECH.IdEmpresa = Session[ConstSessionVar.EMPRESA].ToString();
         DataTable dt = objBOCH.GetList(objECH);
         this.GridSetDataBinding(grdList, dt);

         this.tabMaster.ActiveTabIndex = 0;
         this.StDatosGenerados = ConstFlagEstado.DESACTIVADO;

      }

      public override void RegisterGeneralScripts()
      {
         StringBuilder sb = new StringBuilder();

         sb.AppendLine("function validateEditForm(key){");
         sb.AppendLine("menu_doPostBack('" + mnuToolbar.ClientID + "','" + mnuToolbar.UniqueID + "',key);");
         sb.AppendLine("}");


         sb.AppendLine("function validateEditFormGrid(key){");
         sb.AppendLine("debugger;");
         sb.AppendLine("switch(key){");
         sb.AppendLine("   case '" + _BUTTON_IMPORTFIELD + "' :");
         sb.AppendLine("      var varRpta = isEmptyControl('" + this.txtDocExcel.ClientID + "','Seleccione un archivo Execel');");
         sb.AppendLine("      if(varRpta==true)");
         sb.AppendLine("      return !varRpta;");
         sb.AppendLine("      var extension = document.getElementById('" + this.txtDocExcel.ClientID + "').value;");
         sb.AppendLine("      extension = (extension.substring(extension.lastIndexOf('.'))).toLowerCase();");
         sb.AppendLine("      if(extension != '.xls' && extension != '.xlsx'){");
         sb.AppendLine("     AtentionAlert('Solo archivos en formato .xls | .xlsx'); return false;}");
         sb.AppendLine("      break;");
         sb.AppendLine("   case '" + _BUTTON_IMPVACA + "' :");
         sb.AppendLine("      if('" + Request.QueryString["IdPlanilla"].ToString() + "'!= '" + ConstPlanilla.VACACIONES_OBRERO + "' && '" + Request.QueryString["IdPlanilla"].ToString() + "'!= '" + ConstPlanilla.VACACIONES_EMPLEADO + "'  &&  '" + Request.QueryString["IdPlanilla"].ToString() + "'!= '" + ConstPlanilla.VACACIONES_FLJ + "'){");
         sb.AppendLine("     AtentionAlert('No es una Planilla de Vacaciones')");
         sb.AppendLine("      }");
         sb.AppendLine("      break;");
         sb.AppendLine("}");
         sb.AppendLine("menu_doPostBack('" + mnuGrid.ClientID + "','" + mnuGrid.UniqueID + "',key);");
         sb.AppendLine("}");

         ScriptManager.RegisterStartupScript(this, this.GetType(), "ScriptRegister", sb.ToString(), true);

         RegisterEditPopupScripts();
      }

      public void RegisterEditPopupScripts()
      {
         StringBuilder sb = new StringBuilder();

         sb.AppendLine("function validate" + this.bttOkPopup.ID + "(){");
         sb.AppendLine("varRpta = isEmptyControl('" + this.txtdsNewCampo.ClientID + "','Ingrese la denomicacion del nuevo campo.');");
         sb.AppendLine("if(varRpta==true)");
         sb.AppendLine("return !varRpta;");
         sb.AppendLine("return true;}");

         ScriptManager.RegisterStartupScript(this, this.GetType(), "validatePopup", sb.ToString(), true);

         this.bttOkPopup.OnClientClick = "return validate" + bttOkPopup.ID + "();";
         this.bttCancelPopup.OnClientClick = "$find('" + this.mdlPopup.ClientID + "').hide();return false;";

      }

      protected void mnuToolbar_MenuItemClick(Object sender, MenuEventArgs e)
      {
         if (e.Item == null)
            return;

         switch (e.Item.Value)
         {
            case ConstMenuToolbarValue.BUTTON_SAVE:
            case ConstMenuToolbarValue.BUTTON_SAVENEW:
               if (this.FormEditAction != FormEditAction.Delete)
                  this.SaveData(e.Item.Value);
               else
                  this.DeleteData();
               break;

            case ConstMenuToolbarValue.BUTTON_EXIT:
               this.Response.Redirect("wfImportDataBnd.aspx?Filter=1");
               break;
         }

      }

      protected void mnuGrid_MenuItemClick(Object sender, MenuEventArgs e)
      {
         if (e.Item == null)
            return;

         switch (e.Item.Value)
         {
            case ConstMenuToolbarValue.BUTTON_NEW:
               this.GridEditAction = GridEditAction.AddNew;
               this.txtdsNewCampo.Text = "";
               this.lblTitlePopup.Text = "Configuracion Hora (Nuevo)";
               this.mdlPopup.Show();
               break;
            case _BUTTON_IMPORTFIELD:
               this.lblTituloPopupConfi.Text = "Configuracion de Importacion";
               this.LoadDataEditPopupConfi();
               this.mdlPopupConfi.Show();
               //this.ExcelToDataTable();
               this.StDatosGenerados = ConstFlagEstado.ACTIVADO;
               break;

            case _BUTTON_IMPORTDATA:
               this.MigrarData(_BUTTON_IMPORTDATA);
               this.tabMaster.ActiveTabIndex = 1;
               this.StDatosGenerados = ConstFlagEstado.ACTIVADO;
               break;
            case _BUTTON_GENERATEDOC:
               this.MigrarData(_BUTTON_GENERATEDOC);
               this.tabMaster.ActiveTabIndex = 1;
               this.StDatosGenerados = ConstFlagEstado.ACTIVADO;
               break;
            case _BUTTON_IMPVACA:
               this.MigrarVacaciones();
               break;
         }

      }

      public void MigrarVacaciones()
      {
          RHBOMnt.IProcPlaHora objPro = (RHBOMnt.IProcPlaHora)WCFHelper.GetObject<RHBOMnt.IProcPlaHora>(typeof(RHBOMnt.ProcPlaHora));
          EProcPlaHora objE = new EProcPlaHora();
          objE.IdPeriodo = Session[ConstSessionVar.PERIODO].ToString();
          objE.IdEmpresa = Session[ConstSessionVar.EMPRESA].ToString();
          objE.IdForPago = Request.QueryString["idForPago"];
          objE.IdPlanilla = Request.QueryString["IdPlanilla"];
          objE.NuProcAnual = int.Parse(Request.QueryString["NuProcAnual"]);
          objPro.ExportarVacaciones(objE);
          this.hdnMsgOPB.Value = this.CreatePostbackMessage("CORRECTO", "Los Datos se Importaron Correctamente", TypeMessageAlert.correct, false, "wfImportDataBnd.aspx?Filter=1");

      }

      public void LoadDataEditPopupConfi()
      {
         ddlidHojaExcel.Items.Clear();
         if (this.DataSourceExcel != null)
            this.DataSourceExcel.Rows.Clear();
         HttpPostedFile HttpFileUpload = this.fuDocExcel.PostedFile;
         if (HttpFileUpload == null || HttpFileUpload.ContentLength == 0)
            return;

         GetConnection = ExcelHelper.GetConnectionExcel(HttpFileUpload, Server);

         DataTable dt = DataHelper.RetrieveSheetName(GetConnection[0]);
         WebHelper.LoadListControl(ddlidHojaExcel, dt, "TABLE_NAME", "TABLE_NAME", true, true);

      }

      public override void SaveData(String key)
      {
         if (this.ValidateData() == false)
            return;

         String[] strRet = null;
         switch (this.ddlidTipoMigra.SelectedItem.Value)
         {

            case ConstTipoMigracion.HORAS:
               IEntityBase objE = (IEntityBase)this.CreateEntitySet();
               IBOUpdate objPro = (IBOUpdate)WCFHelper.GetObject<IBOUpdate>(typeof(RHBOMnt.ProcPlaHora));
               strRet = objPro.UpdateData(objE);
               break;
            case ConstTipoMigracion.REGULARIZACION:
            case ConstTipoMigracion.BONIFICACION:
               IEntityBase objEReg = (IEntityBase)this.CreateEntitySetReguBoni();
               IBOUpdate objProReg = (IBOUpdate)WCFHelper.GetObject<IBOUpdate>(typeof(RHBOMnt.ProcPlaReg));
               strRet = objProReg.UpdateData(objEReg);
               break;
         }

         if (strRet == null)
            this.hdnMsgOPB.Value = this.CreatePostbackMessage("CORRECTO", "Los Datos se guardaron correctamente", TypeMessageAlert.correct, false, "wfImportDataBnd.aspx?Filter=1");
         else
            this.hdnMsgOPB.Value = this.CreatePostbackMessage("ATENCIÓN", "- Los Codigos : \n" + strRet[0].ToString() + " No se encuentran registrados. \n", TypeMessageAlert.atention, false, "wfImportDataBnd.aspx?Filter=1");

      }

      protected void ddlidHojaExcel_IndexChanged(Object sender, EventArgs e)
      {
         this.ExcelToDataTable();
         this.mdlPopupConfi.Show();
      }

      public void ExcelToDataTable()
      {

         try
         {
            this.DataSourceExcel = DataHelper.RetrieveData(GetConnection[0], ddlidHojaExcel.SelectedItem.Value);
         }
         catch
         {
            this.hdnMsgOPB.Value = this.CreatePostbackMessage("ATENCIÓN", "Es posible que la hoja seleccionda se encuentre oculta o no se pueda leer.", TypeMessageAlert.atention, false, "");
            if (this.DataSourceExcel != null)
               this.DataSourceExcel.Rows.Clear();
            return;
         }

         int intindex = 0;
         foreach (DataColumn col in this.DataSourceExcel.Columns)
         {
            DataRow dr = this.DataSource.NewRow();
            dr["idEmpresa"] = Session[ConstSessionVar.EMPRESA].ToString();
            dr["dsHoraExcel"] = col.ColumnName;
            dr["idHoraExcel"] = intindex;
            dr["stAnulado"] = ConstFlagEstado.DESACTIVADO;
            this.DataSource.Rows.Add(dr);
            intindex++;
         }

         File.Delete(Server.MapPath(GetConnection[1]));

         this.grdListCampos.DataSource = this.DataSource;
         grdListCampos.DataBind();
         this.mnuGrid.Items[2].ImageUrl = "../Images/Icons/Enabled/ImportTable.png";
         this.txtDocExcel.Text = "";

      }

      protected void grdList_RowDataBound(Object sender, GridViewRowEventArgs e)
      {
         if (e.Row.RowType == DataControlRowType.DataRow)
         {
            DropDownList ddl = (DropDownList)e.Row.FindControl("ddlidHora");
            WebHelper.LoadListControl(ddl, DataSourceDrop, "dsHora", "idHora", true, true);
            WebHelper.ListControlSetValue(ddl, e.Row.Cells[_GRDLIST_IDHORA].Text);
            RadioButton rdb = (RadioButton)e.Row.FindControl("rdbidPersonal");
            if (e.Row.Cells[_GRDLIST_STIDPERSONAL].Text == ConstFlagEstado.ACTIVADO)
               rdb.Checked = true;
         }
      }

      protected void grdListCampos_RowDataBound(Object sender, GridViewRowEventArgs e)
      {
         if (e.Row.RowType == DataControlRowType.Header)
         {
            CheckBox chkAllChecked = new CheckBox();
            chkAllChecked.ID = "chkAllCheck";
            chkAllChecked.Checked = false;
            chkAllChecked.Attributes.Add("onClick", "SelectedCheckBoxAll(this);");
            e.Row.Cells[0].Controls.Add(chkAllChecked);
         }
      }

      protected void grdListData_RowDataBound(Object sender, GridViewRowEventArgs e)
      {
         if (e.Row.RowType != DataControlRowType.DataRow)
            return;

         int intIdx = 0;

         if (this.StDatosGenerados == ConstFlagEstado.ACTIVADO)
         {
            foreach (DataRow dr in this.DataSource.Rows)
            {
               if ("" != dr["idHora"].ToString() && "dsObserva" != dr["idHora"].ToString() && "idConRemu" != dr["idHora"].ToString())
               {
                  esdNumericTextBox objNumText = new esdNumericTextBox();
                  objNumText.NumericType = NumericType.Decimal;
                  objNumText.Width = 30;
                  objNumText.ID = "colum_" + e.Row.RowIndex + "_" + intIdx.ToString();
                  objNumText.Text = e.Row.Cells[intIdx].Text;
                  e.Row.Cells[intIdx].Controls.Add(objNumText);
               }
               else
               {
                  if ("dsObserva" == dr["idHora"].ToString())
                  {
                     esdTextBox objNumText = new esdTextBox();
                     objNumText.Width = 150;
                     objNumText.ID = "colum_" + e.Row.RowIndex + "_" + intIdx.ToString();
                     objNumText.Text = e.Row.Cells[intIdx].Text;
                     e.Row.Cells[intIdx].Controls.Add(objNumText);
                  }
                  if ("idConRemu" == dr["idHora"].ToString())
                  {
                     esdTextBox objNumText = new esdTextBox();
                     objNumText.Width = 30;
                     objNumText.ID = "colum_" + e.Row.RowIndex + "_" + intIdx.ToString();
                     objNumText.Text = e.Row.Cells[intIdx].Text;
                     e.Row.Cells[intIdx].Controls.Add(objNumText);
                  }
               }
               intIdx++;
            }
         }
         else
         {
            foreach (DataControlFieldCell dc in e.Row.Cells)
            {
               if (((System.Web.UI.WebControls.BoundField)(dc.ContainingField)).DataField != "idPersonal" && ((System.Web.UI.WebControls.BoundField)(dc.ContainingField)).DataField != "dsApeNombres" && ((System.Web.UI.WebControls.BoundField)(dc.ContainingField)).DataField != "dsObserva" && ((System.Web.UI.WebControls.BoundField)(dc.ContainingField)).DataField != "idConRemu")
               {
                  esdNumericTextBox objNumText = new esdNumericTextBox();
                  objNumText.NumericType = NumericType.Decimal;
                  objNumText.Width = 30;
                  objNumText.ID = "colum_" + e.Row.RowIndex + "_" + intIdx;
                  objNumText.Text = dc.Text;
                  dc.Controls.Add(objNumText);
               }
               else
               {
                  if (((System.Web.UI.WebControls.BoundField)(dc.ContainingField)).DataField == "dsObserva")
                  {
                     esdTextBox objNumText = new esdTextBox();
                     objNumText.Width = 150;
                     objNumText.ID = "colum_" + e.Row.RowIndex + "_" + intIdx;
                     objNumText.Text = dc.Text;
                     dc.Controls.Add(objNumText);
                  }
                  if (((System.Web.UI.WebControls.BoundField)(dc.ContainingField)).DataField == "idConRemu")
                  {
                     esdTextBox objNumText = new esdTextBox();
                     objNumText.Width = 30;
                     objNumText.ID = "colum_" + e.Row.RowIndex + "_" + intIdx;
                     objNumText.Text = dc.Text;
                     dc.Controls.Add(objNumText);
                  }
               }
               intIdx++;
            }
         }
         switch (e.Row.Cells[intIdx].Text)
         {
            case "1":
               e.Row.ForeColor = System.Drawing.Color.Orange;
               e.Row.BorderColor = System.Drawing.Color.Orange;
               e.Row.BorderWidth = 1;
               e.Row.BorderStyle = BorderStyle.Solid;  
               break;
            case "2":
               e.Row.ForeColor = System.Drawing.Color.Red;
               e.Row.BorderColor = System.Drawing.Color.Red;
               e.Row.BorderWidth = 1;
               e.Row.BorderStyle = BorderStyle.Solid;
               break;
         }

      }

      protected void bttOkPopup_Click(object sender, EventArgs e)
      {

         Object objResNuSec = null;
         int intResNusec = 0;
         DataTable dt = (DataTable)this.DataSource;
         DataRow dr = null;

         if (this.GridEditAction == GridEditAction.AddNew || this.GridEditAction == GridEditAction.Copy)
         {
            objResNuSec = dt.Compute("MAX(idHoraExcel)", "");
            if (objResNuSec == null || objResNuSec.ToString() == "")
               intResNusec = 0;
            else
               intResNusec = Convert.ToInt32(objResNuSec);
            intResNusec += 1;
            dr = dt.NewRow();
            dr["idHoraExcel"] = intResNusec;
         }
         else
         {
            dr = this.GridGetRowFromDataKey(grdList, this.EditRowIndex);
         }

         if (this.GridEditAction != GridEditAction.Delete)
         {
            dr["idEmpresa"] = Session[ConstSessionVar.EMPRESA].ToString();
            dr["dsHoraExcel"] = this.txtdsNewCampo.Text;
            dr["stAnulado"] = ConstFlagEstado.DESACTIVADO;
         }
         else
         {
            dr["stAnulado"] = ConstFlagEstado.ACTIVADO;
         }

         if (this.GridEditAction == GridEditAction.AddNew || this.GridEditAction == GridEditAction.Copy)
         {
            dt.Rows.Add(dr);
         }

         grdList.DataSource = this.DataSource;
         grdList.DataBind();
      }

      protected void bttOkPopupConfi_Click(object sender, EventArgs e)
      {

         DataTable dt = this.DataSource.Clone();

         foreach (GridViewRow gvr in grdListCampos.Rows)
         {
            if (gvr.RowType == DataControlRowType.DataRow)
            {
               CheckBox chkAllSelect = (CheckBox)gvr.FindControl("chkSelected");

               if (chkAllSelect.Checked)
               {
                  DataRow dr = dt.NewRow();
                  dr.ItemArray = this.DataSource.Rows[gvr.RowIndex].ItemArray;
                  dt.Rows.Add(dr);
               }
            }
         }

         switch (this.ddlidTipoMigra.SelectedItem.Value)
         {
            case ConstTipoMigracion.HORAS:
               EHora objE = new EHora();
               IBOQuery objBO = (IBOQuery)WCFHelper.GetObject<IBOQuery>(typeof(RHBOQry.Hora));
               objE.IdEmpresa = Session[ConstSessionVar.EMPRESA].ToString();
               this.DataSourceDrop = objBO.GetList(objE);
               break;
            case ConstTipoMigracion.REGULARIZACION:
            case ConstTipoMigracion.BONIFICACION:
               this.DataSourceDrop.Rows.Clear();
               DataRow dtnew = this.DataSourceDrop.NewRow();
               dtnew["idHora"] = "idConRemu";
               dtnew["dsHora"] = "Concepto Remunerativo";
               this.DataSourceDrop.Rows.Add(dtnew);
               dtnew = this.DataSourceDrop.NewRow();
               dtnew["idHora"] = "nuHoras";
               dtnew["dsHora"] = "Numero Horas";
               this.DataSourceDrop.Rows.Add(dtnew);
               dtnew = this.DataSourceDrop.NewRow();
               dtnew["idHora"] = "mtRegulaMn";
               dtnew["dsHora"] = "Mt Regula/Boni Mn";
               this.DataSourceDrop.Rows.Add(dtnew);
               dtnew = this.DataSourceDrop.NewRow();
               dtnew["idHora"] = "mtRegulaMe";
               dtnew["dsHora"] = "Mt Regula/Boni Me";
               this.DataSourceDrop.Rows.Add(dtnew);
               dtnew = this.DataSourceDrop.NewRow();
               dtnew["idHora"] = "dsObserva";
               dtnew["dsHora"] = "Observacion";
               this.DataSourceDrop.Rows.Add(dtnew);

               break;

         }

         this.DataSource = dt;
         grdList.DataSource = this.DataSource;
         grdList.DataBind();


      }

      public void MigrarData(string Keyvalue)
      {
         foreach (GridViewRow gvr in grdList.Rows)
         {
            if (gvr.RowType == DataControlRowType.DataRow)
            {
               DropDownList ddl = (DropDownList)gvr.FindControl("ddlidHora");
               RadioButton rdb = (RadioButton)gvr.FindControl("rdbidPersonal");
               this.DataSource.Rows[gvr.RowIndex]["idHora"] = ddl.SelectedItem.Value;
               this.DataSource.Rows[gvr.RowIndex]["stIdPersonal"] = rdb.Checked ? ConstFlagEstado.ACTIVADO : ConstFlagEstado.DESACTIVADO;
            }
         }

         DataTable dtData = new DataTable();
         dtData.TableName = "dtData";

         foreach (DataRow dr in this.DataSource.Rows)
         {
            DataColumn dc = new DataColumn("colum_" + dr["idHoraExcel"].ToString());

            switch (this.ddlidTipoMigra.SelectedItem.Value)
            {
               case ConstTipoMigracion.HORAS:
                  if (dr["idHora"].ToString() == "")
                     dc.DataType = System.Type.GetType("System.String");
                  else
                     dc.DataType = System.Type.GetType("System.Double");
                  break;
               case ConstTipoMigracion.REGULARIZACION:
               case ConstTipoMigracion.BONIFICACION:
                  if (dr["idHora"].ToString() == "" || dr["idHora"].ToString() == "dsObserva")
                     dc.DataType = System.Type.GetType("System.String");
                  else
                     dc.DataType = System.Type.GetType("System.Double");
                  break;

            }

            dtData.Columns.Add(dc);
         }

         DataColumn dcStAnulado = new DataColumn("stAnulado");
         dcStAnulado.DataType = System.Type.GetType("System.String");
         dtData.Columns.Add(dcStAnulado);


         foreach (DataRow drExcel in this.DataSourceExcel.Rows)
         {
            int intLength = drExcel.ItemArray.Length;
            bool addRow = true;

            DataRow drNew = dtData.NewRow();

            foreach (DataRow drcolum in this.DataSource.Rows)
            {
               string value = drExcel[int.Parse(drcolum["idHoraExcel"].ToString())].ToString();

               if (drcolum["stidPersonal"].ToString() == ConstFlagEstado.ACTIVADO)
               {
                  if (value == null || value.Trim() == "")
                  {
                     addRow = false;
                     break;
                  }
                  else
                  {
                     value = "0000000" + value;
                     value = value.Substring(value.Length - 7, 7);
                     drNew["colum_" + drcolum["idHoraExcel"].ToString()] = value;
                           
                     EPersonal objE = new EPersonal();
                     IBOQuery objBO = (IBOQuery)WCFHelper.GetObject<IBOQuery>(typeof(RHBOQry.Personal));
                     objE.IdEmpresa = Session[ConstSessionVar.EMPRESA].ToString();
                     objE.IdPersonal = value;
                     if (objBO.Exists(objE))
                     {
                        EPersonalPlanilla objEP = new EPersonalPlanilla();
                        RHBOQry.IPlanilla objBOP = (RHBOQry.IPlanilla)WCFHelper.GetObject<RHBOQry.IPlanilla>(typeof(RHBOQry.Planilla));
                        objEP.IdEmpresa = Session[ConstSessionVar.EMPRESA].ToString();
                        objEP.IdPersonal = value;
                        objEP.IdPlanilla = txtidPlanilla.Text;
                        if (Request.QueryString["idForPago"] == ConstFormaPago.OFICIAL)
                        {
                            if (objBOP.ExistsPersonalPlanilla(objEP))
                                drNew["stAnulado"] = "0";
                            else
                                drNew["stAnulado"] = "2";
                        }
                        else
                            drNew["stAnulado"] = "0";
                     }
                     else
                     {
                        drNew["stAnulado"] = "1";
                     }
                  }
               }
               else
                  if (Keyvalue == _BUTTON_IMPORTDATA)
                  {
                     if (int.Parse(drcolum["idHoraExcel"].ToString()) < intLength)
                        if (value == "")
                           drNew["colum_" + drcolum["idHoraExcel"].ToString()] = 0.00;
                        else
                           drNew["colum_" + drcolum["idHoraExcel"].ToString()] = value;
                     else
                        if ("" == drcolum["idHora"].ToString())
                           drNew["colum_" + drcolum["idHoraExcel"].ToString()] = "";
                        else
                           drNew["colum_" + drcolum["idHoraExcel"].ToString()] = Math.Round(0.0, 2);
                  }
                  else
                     drNew["colum_" + drcolum["idHoraExcel"].ToString()] = Math.Round(0.0, 2);
            }

            if (addRow == true)
            {
               dtData.Rows.Add(drNew);
            }
         }

         this.grdListData.Columns.Clear();

         foreach (DataRow drcol in this.DataSource.Rows)
         {
            BoundField bfield = new BoundField();
            bfield.DataField = "colum_" + drcol["idHoraExcel"].ToString();
            bfield.HeaderText = drcol["dsHoraExcel"].ToString();
            this.grdListData.Columns.Add(bfield);
         }

         BoundField bfieldA = new BoundField();
         bfieldA.DataField = "stAnulado";
         bfieldA.HeaderStyle.CssClass ="hideDataGridColumn";
         bfieldA.ItemStyle.CssClass = "hideDataGridColumn";
         this.grdListData.Columns.Add(bfieldA);
         
         this.DataSourceData = dtData;

         this.grdListData.DataSource = this.DataSourceData;
         this.grdListData.DataBind();

         Object objResNuSec = null;
         int intResNusec = 0;

         objResNuSec = DataSourceData.Compute("COUNT(stAnulado)", "stAnulado='0'");
         if (objResNuSec == null || objResNuSec.ToString() == "")
            intResNusec = 0;
         else
            intResNusec = Convert.ToInt32(objResNuSec);

         lblMessageLog.Text = "Total CORRECTOS = " + intResNusec + "<br/>";


         objResNuSec = DataSourceData.Compute("COUNT(stAnulado)", "stAnulado='1'");
         if (objResNuSec == null || objResNuSec.ToString() == "")
            intResNusec = 0;
         else
            intResNusec = Convert.ToInt32(objResNuSec);

         lblMessageLog.Text = lblMessageLog.Text + "Total NO EXISTEN = " + intResNusec + "<br/>";

         objResNuSec = DataSourceData.Compute("COUNT(stAnulado)", "stAnulado='2'");
         if (objResNuSec == null || objResNuSec.ToString() == "")
            intResNusec = 0;
         else
            intResNusec = Convert.ToInt32(objResNuSec);

         lblMessageLog.Text = lblMessageLog.Text + "Total NO PERTENECEN A LA PLANILLA = " + intResNusec + "<br/>";

      }

      public override Object CreateEntitySet()
      {

         DataTable dt = (DataTable)this.DataSourceData;

         DataTable dtChange = null;
         dtChange = dt.GetChanges(DataRowState.Added);
         dtChange = dt.GetChanges(DataRowState.Modified);

         IList<EProcPlaHora> colEProcPlaH = new List<EProcPlaHora>();
         foreach (GridViewRow gvr in this.grdListData.Rows)
         {
            if (gvr.RowType == DataControlRowType.DataRow)
            {
               string strIdPer = "";
               if (this.StDatosGenerados == ConstFlagEstado.ACTIVADO)
               {
                  int intinx = 0;
                  foreach (DataRow drcol in this.DataSource.Rows)
                  {

                     if (drcol["stIdPersonal"].ToString() == ConstFlagEstado.ACTIVADO)
                     {
                        strIdPer = "0000000" + gvr.Cells[intinx].Text;
                        strIdPer = strIdPer.Substring(strIdPer.Length - 7, 7);
                     }
                     else
                        if (drcol["idHora"].ToString() != "")
                        {
                           EProcPlaHora objE = new EProcPlaHora();
                           objE.IdPeriodo = Session[ConstSessionVar.PERIODO].ToString();
                           objE.IdEmpresa = Session[ConstSessionVar.EMPRESA].ToString();
                           objE.IdForPago = Request.QueryString["idForPago"];
                           objE.IdPlanilla = Request.QueryString["IdPlanilla"];
                           objE.NuProcAnual = int.Parse(Request.QueryString["NuProcAnual"]);
                           objE.IdPersonal = strIdPer;
                           objE.IdHora = drcol["idHora"].ToString();
                           objE.IdMes = Request.QueryString["idMes"]; 
                           objE.NuHoras = decimal.Parse(gvr.Cells[intinx].Text);
                           objE.StAnulado = ConstFlagEstado.DESACTIVADO;
                           objE.EntityState = EntityState.Added;

                           if (gvr.Cells[gvr.Cells.Count - 1].Text == "0")
                              colEProcPlaH.Add(objE);
                        }
                     intinx++;
                  }
                  
               }
               else
               {
                  foreach (DataControlFieldCell dc in gvr.Cells)
                  {
                     if (((System.Web.UI.WebControls.BoundField)(dc.ContainingField)).DataField == "idPersonal")
                     {
                        strIdPer = "0000000" + dc.Text;
                        strIdPer = strIdPer.Substring(strIdPer.Length - 7, 7);
                     }
                     else
                     {
                        if (((System.Web.UI.WebControls.BoundField)(dc.ContainingField)).DataField != "dsApeNombres")
                        {
                           EProcPlaHora objE = new EProcPlaHora();
                           objE.IdPeriodo = Session[ConstSessionVar.PERIODO].ToString();
                           objE.IdEmpresa = Session[ConstSessionVar.EMPRESA].ToString();
                           objE.IdForPago = Request.QueryString["idForPago"];
                           objE.IdPlanilla = Request.QueryString["IdPlanilla"];
                           objE.NuProcAnual = int.Parse(Request.QueryString["NuProcAnual"]);
                           objE.IdPersonal = strIdPer;
                           objE.IdHora = ((System.Web.UI.WebControls.BoundField)(dc.ContainingField)).DataField;
                           objE.IdMes = Request.QueryString["idMes"]; 
                           objE.NuHoras = decimal.Parse(dc.Text);
                           objE.StAnulado = ConstFlagEstado.DESACTIVADO;
                           objE.EntityState = EntityState.Modified;

                           colEProcPlaH.Add(objE);
                        }

                     }
                  }

               }

            }
         }

         EProcPlaHoraSet objESet = new EProcPlaHoraSet();
         objESet.EProcPlaHora = colEProcPlaH;
         return objESet;
      }

      public Object CreateEntitySetReguBoni()
      {
         IList<EProcPlaReg> colEProcPlaH = new List<EProcPlaReg>();
         foreach (GridViewRow gvr in this.grdListData.Rows)
         {
            if (gvr.RowType == DataControlRowType.DataRow)
            {
               string strIdPer = "";
               string strIdConRemu = "";
               if (this.StDatosGenerados == ConstFlagEstado.ACTIVADO)
               {
                  EProcPlaReg objE = new EProcPlaReg();
                  objE.IdPeriodo = Session[ConstSessionVar.PERIODO].ToString();
                  objE.IdEmpresa = Session[ConstSessionVar.EMPRESA].ToString();
                  objE.IdForPago = Request.QueryString["idForPago"];
                  objE.IdPlanilla = Request.QueryString["IdPlanilla"];
                  objE.NuProcAnual = int.Parse(Request.QueryString["NuProcAnual"]);
                  int intinx = 0;
                  foreach (DataRow drcol in this.DataSource.Rows)
                  {

                     if (drcol["stIdPersonal"].ToString() == ConstFlagEstado.ACTIVADO)
                     {
                        strIdPer = "0000000" + gvr.Cells[intinx].Text;
                        strIdPer = strIdPer.Substring(strIdPer.Length - 7, 7);
                        objE.IdPersonal = strIdPer;
                     }
                     else
                        if (drcol["idHora"].ToString() != "")
                        {
                           switch (drcol["idHora"].ToString())
                           {
                              case "idConRemu":
                                 strIdConRemu = "000" + gvr.Cells[intinx].Text;
                                 strIdConRemu = strIdConRemu.Substring(strIdConRemu.Length - 3, 3);
                                 objE.IdConRemu = strIdConRemu;
                                 break;
                              case "nuHoras":
                                 objE.NuHoras = decimal.Parse(gvr.Cells[intinx].Text);
                                 break;
                              case "mtRegulaMn":
                                 objE.MtRegulaMn = decimal.Parse(gvr.Cells[intinx].Text);
                                 break;
                              case "mtRegulaMe":
                                 objE.MtRegulaMe = decimal.Parse(gvr.Cells[intinx].Text);
                                 break;
                              case "dsObserva":
                                 objE.DsObserva = gvr.Cells[intinx].Text;
                                 break;
                           }

                        }

                     intinx++;
                  }
                  if (this.ddlidTipoMigra.SelectedItem.Value == ConstTipoMigracion.REGULARIZACION)
                     objE.IdTipRegula = ConstTipoRegularizacion.REGULARIZACION;
                  else
                     objE.IdTipRegula = ConstTipoRegularizacion.BONIFICACION;

                  objE.StAnulado = ConstFlagEstado.DESACTIVADO;
                  objE.EntityState = EntityState.Added;

                  if (gvr.Cells[gvr.Cells.Count - 1].Text == "0")
                     colEProcPlaH.Add(objE);

               }

            }
         }

         EProcPlaRegSet objESet = new EProcPlaRegSet();
         objESet.EProcPlaReg = colEProcPlaH;
         return objESet;
      }

   }
}